package org.example.day05;

/**
 * 第二章节2.2.9.3: 类锁 synchronized修饰静态方法，默认类锁是类.class。
 *                  和synchronized(类.class)效果一样.
 */
public class MyThread7 {
    //用到的锁是MyThread7.class
    public static void printA(){
        synchronized (MyThread7.class){
            try {
                System.out.println("线程名称为: " + Thread.currentThread().getName() + " 进入printA的时间: " + System.currentTimeMillis());
                Thread.sleep(3000);
                System.out.println("线程名称为: " + Thread.currentThread().getName() + " 推出printA: " + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //用到的锁是MyThread7.class 达到了同步
    synchronized public static void printB(){
        System.out.println("线程名称为: " + Thread.currentThread().getName() + " 进入printB的时间: " + System.currentTimeMillis());
        System.out.println("线程名称为: " + Thread.currentThread().getName() + " 推出printB: " + System.currentTimeMillis());
    }

    public static void main(String[] args) {
        MyThread7 m71 = new MyThread7();
        MyThread7 m72 = new MyThread7();
        Thread7A ta = new Thread7A(m71);
        ta.setName("A");
        ta.start();
        Thread7B tb = new Thread7B(m72);
        tb.setName("B");
        tb.start();
    }
}

class Thread7A extends Thread{
    private MyThread7 m7;

    public Thread7A(MyThread7 m7) {
        this.m7 = m7;
    }

    @Override
    public void run() {
        m7.printA();
    }
}

class Thread7B extends Thread{
    private MyThread7 m7;

    public Thread7B(MyThread7 m7) {
        this.m7 = m7;
    }

    @Override
    public void run() {
        m7.printB();
    }
}
